package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.ResponseResult;
import com.example.model.entity.MemoInfo;
import com.example.model.entity.UserInfo;
import com.example.service.MemoInfoService;
import com.example.util.DateUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ling
 * @since 2024-08-15
 */
@RestController
@RequestMapping("/memo-info")
public class MemoInfoController {

    @Autowired
    private MemoInfoService memoInfoService;


    /**
     * 添加
     * @return
     */
    @PostMapping("/add")
    public ResponseResult add(@RequestBody MemoInfo memoInfo){
        memoInfo.setCreateTime(new Date());
        memoInfo.setStatus(0);
        memoInfoService.save(memoInfo);
        return new ResponseResult();
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    public ResponseResult delete(Integer id){
        memoInfoService.removeById(id);
        return new ResponseResult();
    }

    /**
     * 更新
     * @return
     */
    @PostMapping("/update")
    public ResponseResult update(@RequestBody MemoInfo memoInfo){
        memoInfoService.updateById(memoInfo);
        return new ResponseResult();
    }

    @PostMapping("/complete")
    public ResponseResult complete(@RequestBody MemoInfo memoInfo){
        memoInfo.setStatus(1);
        memoInfo.setCompleteTime(new Date());
        memoInfoService.updateById(memoInfo);
        return new ResponseResult();
    }



    /**
     * 获取列表
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public ResponseResult list(Integer page,Integer size,Integer userId,String memoName,Integer showType){
        if(!Objects.isNull(page)){
            PageHelper.startPage(page,size);
        }
        QueryWrapper<MemoInfo> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(memoName)){
            queryWrapper.like("memo_name","%"+memoName+"%");
        }
        queryWrapper.eq("user_id",userId);
        PageHelper.orderBy("create_time desc");
        if(!Objects.isNull(showType)){
            if(showType == 0){
                Date date1 = DateUtils.getMonthEnd(TimeZone.getTimeZone("GMT+8"),new Date());
                Date date2 = DateUtils.getMonthStart(TimeZone.getTimeZone("GMT+8"),new Date());
                //按月
                queryWrapper.gt("end_time", date2);
                queryWrapper.lt("start_time",date1);
            }else if(showType == 1){
                //按周
                Calendar calendar = Calendar.getInstance();
                // 设置为本周的第一天（默认为周日）
                calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMinimum(Calendar.HOUR_OF_DAY));
                calendar.set(Calendar.MINUTE, calendar.getActualMinimum(Calendar.MINUTE));
                calendar.set(Calendar.SECOND, calendar.getActualMinimum(Calendar.SECOND));
                Date date1 = calendar.getTime();

                queryWrapper.gt("end_time", date1);

                Date date2 = new Date(date1.getTime()+(1000*60*60*24*7));
                queryWrapper.lt("start_time",date2);
            }
        }
        PageInfo<MemoInfo> pageInfo = new PageInfo<>(memoInfoService.list(queryWrapper));
        List<MemoInfo> list = pageInfo.getList();
        long nowTime = System.currentTimeMillis();
        for(MemoInfo memoInfo:list){
            if(nowTime > memoInfo.getEndTime().getTime() && memoInfo.getStatus() == 0){
                memoInfo.setStatus(2);
                memoInfoService.updateById(memoInfo);
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("list",list);
        resultMap.put("total",pageInfo.getTotal());
        return new ResponseResult(resultMap);
    }


    /**
     * 获取逾期提醒列表
     * @param userId
     * @return
     */
    @GetMapping("/remind-list")
    public ResponseResult remindList(Integer userId){
        QueryWrapper<MemoInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<MemoInfo> memoInfoList = memoInfoService.list(queryWrapper);
        long nowTime = System.currentTimeMillis();

        List<MemoInfo> memoInfoListNew = new ArrayList<>();
        for(MemoInfo memoInfo:memoInfoList){
            if(nowTime > memoInfo.getEndTime().getTime() && memoInfo.getStatus() == 0){
                memoInfo.setStatus(2);
                memoInfoService.updateById(memoInfo);
                break;
            }
            if(memoInfo.getStatus() == 0){
                long time = memoInfo.getEndTime().getTime() - nowTime;
                if(time < 1000*60*60){
                    memoInfo.setMessage("剩余"+time/1000/60+"分钟即将预期！！");
                    //需要提醒预期
                    memoInfoListNew.add(memoInfo);
                }
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("list",memoInfoListNew);
        return new ResponseResult(resultMap);
    }

    @GetMapping("/home-page")
    public ResponseResult homePage(Integer userId){
        Date nowDate = new Date();

        Map<String,Object> countMap = new HashMap<>();
        //即将到来事务数
        QueryWrapper<MemoInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("status",0);
        queryWrapper.lt("start_time",nowDate);
        countMap.put("aboutCount",memoInfoService.count(queryWrapper));
        //进行中的事务数
        QueryWrapper<MemoInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id",userId);
        queryWrapper1.gt("start_time",nowDate);
        queryWrapper1.lt("end_time",nowDate);
        queryWrapper1.eq("status",0);
        countMap.put("runCount",memoInfoService.count(queryWrapper1));
        //已完成事务数
        QueryWrapper<MemoInfo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("user_id",userId);
        queryWrapper2.eq("status",1);
        countMap.put("completeCount",memoInfoService.count(queryWrapper2));
        //已逾期事务数
        QueryWrapper<MemoInfo> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("user_id",userId);
        queryWrapper3.ne("status",1);
        queryWrapper3.lt("end_time",nowDate);
        countMap.put("overdueCount",memoInfoService.count(queryWrapper3));

        Map<String,Object> result = new HashMap<>();
        result.put("countMap",countMap);
        return new ResponseResult(result);
    }

}
